<template>
  <!-- 移动端预览 -->
  <van-form
    v-if="formConf && formList.length"
    :model="formModel"
    :ref="formConf.formRef"
    :label-width="formConf.labelWidth"
    label-align="top"
    :disabled="formConf.disabled"
    show-error-message
  >
    <phone-form-row-container
      :list.sync="list"
      :formConf="formConf"
      :onlyShow="onlyShow"
    />
  </van-form>
</template>

<script>
import {
  deepClone,
  toCamelCase,
  traverseTree,
  objectToArray,
} from "../utils/index";
import phoneFormRowContainer from "../formComponents/phoneComponents/layoutComs/formRowContainer.vue";
export default {
  name: "phoneForm",
  components: { phoneFormRowContainer },
  props: {
    // 表单属性
    formConf: {
      type: Object,
      default: () => {},
    },
    // 表单列表
    formList: {
      type: Array,
      default: () => [],
    },
    onlyShow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formModel: {},
      list: [],
    };
  },
  watch: {
    formList: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        if (newValue) {
          this.list = deepClone(newValue);
        }
      },
    },
    list: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          // 根据表单列表生成动态表单模型数据
          this.getFormModel(newValue);
          console.log("formData:", JSON.stringify(this.formModel));
        }
      },
    },
  },
  computed: {
    // 存放表单 key 键名 value 键值 type 值类型
    modelArray() {
      return objectToArray(this.formModel);
    },
  },
  methods: {
    toCamelCase,
    // 根据表单列表生成动态表单模型数据
    getFormModel(list) {
      list.forEach((el) => {
        if (el.__vModel__ && el.__config__) {
          let obj = JSON.parse(JSON.stringify(this.formModel));
          this.formModel = Object.assign(obj, {
            [el.__vModel__]: el.__config__.defaultValue,
          });
        }
        if (el.children) {
          this.getFormModel(el.children);
        }
      });
    },
    submitForm(cb) {
      this.$emit("update:formList", this.list);
      this.$emit("submit", this.formModel);
      cb(this.modelArray, deepClone(this.list));
    },
    validateForm(cb) {
      this.$emit("update:formList", this.list);
      this.$refs[this.formConf.formRef]
        .validate()
        .then(() => {
          this.$emit("submit", this.formModel);
          cb(true, this.modelArray, deepClone(this.list));
        })
        .catch((error) => {
          //检验失败
          cb(false, this.formModel, deepClone(this.list));
        });
    },
    // 重置
    resetForm() {
      this.$refs[this.formConf.formRef].resetValidation();
      traverseTree(this.list, (node) => {
        if (node.__config__) node.__config__.defaultValue = null;
      }); // 从根节点开始遍历整个树
      this.$emit("update:formList", this.list);
    },
  },
};
</script>

<style lang="scss"></style>
